package com.ddpt.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lh.center.common.base.BizServiceImpl;
import com.lh.center.common.constant.GlobalConstant;
import com.lh.center.common.enums.AdminService;
import com.lh.center.common.exception.CommonException;
import com.lh.center.common.exception.ErrorEnum;
import com.lh.center.common.util.BeanTransferUtils;
import com.lh.center.permission.api.entity.Permission;
import com.lh.center.permission.api.entity.Role;
import com.lh.center.permission.api.session.SessionPermission;
import com.lh.center.permission.mapper.PermissionMapper;
import com.lh.center.permission.mapper.RoleMapper;
import com.lh.center.permission.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author czy
 * @since 2022-04-07
 */
@Service
public class RoleServiceImpl extends BizServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<SessionPermission> queryBackAdminPermission(Integer type, Long roleId) {
        //超管，查询所有SaaS后台的可用权限
        if(GlobalConstant.SUPER_ADMIN.equals(type)) {
            LambdaQueryWrapper<Permission> permiWrapper = Wrappers.lambdaQuery(Permission.class);
            permiWrapper.eq(Permission::getAdminService, AdminService.BACK);
            permiWrapper.eq(Permission::getStatus,GlobalConstant.ONE);
            permiWrapper.eq(Permission::getDeleted,GlobalConstant.ZERO);
            List<Permission> permissionList = permissionMapper.selectList(permiWrapper);
            return BeanTransferUtils.transferCollection(permissionList,SessionPermission.class);
        }
        Role role = getById(roleId);
        if(null == role || GlobalConstant.ONE.equals(role.getDeleted())) {
            throw new CommonException(ErrorEnum.CURRENT_ROLE_INVALID);
        }
        return permissionMapper.querySessionPermissionByRole(roleId);
    }
}
